﻿using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Profile;

namespace DJY.Code.Helper
{
    public class MailMsgHelper
    {
        #region 邮件发送 SendCloud 每天免费200封
        /// <summary>
        /// 邮件发送 添加附件
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="paramKey">文件主键</param>
        /// <param name="fileName">显示文件名</param>
        /// <returns></returns>
        private static StreamContent createStream(String filePath, String paramKey, String fileName)
        {
            FileStream fs = File.OpenRead(filePath);
            StreamContent streamContent = new StreamContent(fs);
            streamContent.Headers.Add("Content-Type", "application/octet-stream");
            String headerValue = "form-data; name=\"" + paramKey + "\"; filename=\"" + fileName + "\"";
            byte[] bytes1 = Encoding.UTF8.GetBytes(headerValue);
            headerValue = "";
            foreach (byte b1 in bytes1)
            {
                headerValue += (Char)b1;
            }
            streamContent.Headers.Add("Content-Disposition", headerValue);
            return streamContent;
        }

        public static bool SendEmail(string tos, string fromName, string subject, string htmlBody)
        {
            bool isSended = false;
            String url = "http://api.sendcloud.net/apiv2/mail/send";

            String api_user = "wolifor_test_jcb0fl";
            String api_key = "RoEl3dvptQM4Fip4";


            HttpClient client = null;
            HttpResponseMessage response = null;

            try
            {
                client = new HttpClient();

                List<KeyValuePair<String, String>> paramList = new List<KeyValuePair<String, String>>();
                paramList.Add(new KeyValuePair<string, string>("apiUser", api_user));
                paramList.Add(new KeyValuePair<string, string>("apiKey", api_key));
                paramList.Add(new KeyValuePair<string, string>("from", "jczd@email.zjjczd.com"));
                paramList.Add(new KeyValuePair<string, string>("fromName", fromName));
                paramList.Add(new KeyValuePair<string, string>("to", tos));
                paramList.Add(new KeyValuePair<string, string>("subject", subject));
                paramList.Add(new KeyValuePair<string, string>("html", htmlBody));

                var multipartFormDataContent = new MultipartFormDataContent();
                foreach (var keyValuePair in paramList)
                {
                    multipartFormDataContent.Add(new StringContent(keyValuePair.Value), String.Format("\"{0}\"", keyValuePair.Key));
                }

                //multipartFormDataContent.Add(createStream("D:\\附件2.txt", "attachments", "附件名称2.txt"));

                //multipartFormDataContent.Add(createStream("D:\\附件1.txt", "attachments", "附件名称1.txt"));

                response = client.PostAsync(url, multipartFormDataContent).Result;

                String result = response.Content.ReadAsStringAsync().Result;

                var resultSend = Newtonsoft.Json.JsonConvert.DeserializeObject<emailmsgObj>(result.ToString());
                if (resultSend.result == true && resultSend.statusCode == 200)
                {
                    isSended = true;
                }
                else
                {
                    isSended = false;
                }
                //Console.WriteLine("result:{0}", result);
            }
            catch (Exception e)
            {
                //Console.WriteLine("\nException Caught!");
                //Console.WriteLine("Message :{0} ", e.Message);
            }
            finally
            {
                if (null != client)
                {
                    client.Dispose();
                }
            }
            return isSended;
        }
        #endregion


        #region 短信发送 SendCloud 每天免费20条
        //private static String generate_md5(String str)
        //{
        //    MD5 md5 = new MD5CryptoServiceProvider();

        //    //compute hash from the bytes of text
        //    md5.ComputeHash(Encoding.GetEncoding("utf-8").GetBytes(str));

        //    //get hash result after compute it
        //    byte[] result = md5.Hash;

        //    StringBuilder strBuilder = new StringBuilder();
        //    for (int i = 0; i < result.Length; i++)
        //    {
        //        strBuilder.Append(result[i].ToString("x2"));
        //    }

        //    return strBuilder.ToString();
        //}

        //public static bool SendMsg(string mobile, string code)
        //{
        //    return Send(mobile, "29536", code);
        //}
        //public static bool SendLoginMsg(string mobile, string code)
        //{
        //    return Send(mobile, "29573", code);
        //}
        //public static bool SendFindPwdMsg(string mobile, string code)
        //{
        //    return Send(mobile, "29578", code);
        //}
        //public static bool SendWelComeMsg(string mobile)
        //{
        //    return Send(mobile, "29537","",true);
        //}



        //private static bool Send(string mobile, string templateId, string code, bool isWelcome = false)
        //{
        //    bool isSended = false;
        //    String url = "http://www.sendcloud.net/smsapi/send";

        //    String smsUser = "wolifor_msg_user";
        //    String smsKey = "tGGg489ilSaVlXRENsqrnsWyjR0Ulb4l";

        //    List<KeyValuePair<String, String>> paramList = new List<KeyValuePair<String, String>>();
        //    paramList.Add(new KeyValuePair<String, String>("smsUser", smsUser));
        //    paramList.Add(new KeyValuePair<String, String>("templateId", templateId));
        //    paramList.Add(new KeyValuePair<String, String>("phone", mobile));
        //    paramList.Add(new KeyValuePair<String, String>("msgType", "0"));
        //    if (!isWelcome)
        //    {
        //        paramList.Add(new KeyValuePair<String, String>("vars", "{\"%code%\":\"" + code + "\"}"));
        //    }
        //    else
        //    {
        //        paramList.Add(new KeyValuePair<String, String>("vars", "{\"%regtime%\":\"" + DateTime.Now.ToString("yyyy-MM-dd hh:mm") + "\"}"));
        //    }
        //    //string vars = string.Format("{{\"%content%\":\"{0}\"}}", templateMessageText.Substring(templateMessageText.IndexOf('】') + 1));
        //    //paramList.Add(new KeyValuePair<String, String>("vars", vars));

        //    paramList.Sort(
        //        delegate (KeyValuePair<String, String> p1, KeyValuePair<String, String> p2)
        //        {
        //            return p1.Key.CompareTo(p2.Key);
        //        }
        //    );

        //    var param_str = "";
        //    foreach (var param in paramList)
        //    {
        //        param_str += param.Key.ToString() + "=" + param.Value.ToString() + "&";
        //    }

        //    String sign_str = smsKey + "&" + param_str + smsKey;
        //    String sign = generate_md5(sign_str);

        //    paramList.Add(new KeyValuePair<String, String>("signature", sign));

        //    HttpClient client = null;
        //    HttpResponseMessage response = null;

        //    try
        //    {
        //        client = new HttpClient();
        //        response = client.PostAsync(url, new FormUrlEncodedContent(paramList)).Result;
        //        String result = response.Content.ReadAsStringAsync().Result;
        //        var resultSend = Newtonsoft.Json.JsonConvert.DeserializeObject<emailmsgObj>(result.ToString());
        //        if (resultSend.result == true && resultSend.statusCode == 200)
        //        {
        //            isSended = true;
        //        }
        //        else
        //        {
        //            isSended = false;
        //        }
        //        //Console.WriteLine("result:{0}", result);
        //    }
        //    catch (Exception e)
        //    {
        //        //Console.WriteLine("\nException Caught!");
        //        //Console.WriteLine("Message :{0} ", e.Message);
        //    }
        //    finally
        //    {
        //        if (null != response)
        //        {
        //            response.Dispose();
        //        }
        //        if (null != client)
        //        {
        //            client.Dispose();
        //        }
        //    }
        //    return isSended;
        //}

        #endregion


        #region 阿里云短信发送接口调用 验证身份信息
        private const string ACCESSKEYID = "LTAI2ZM2FU1AXz7s";
        private const string ACCESSSECRET = "YEbKrRd2Dj4YkTNU6wggD4AnyLFFfE";
        #endregion


        #region 阿里云短信验证码发送

        private static bool Send(string mobile, string templateCode, string code, string SignName, bool isWelcome = false)
        {
            log4net.ILog log = log4net.LogManager.GetLogger("InfoLog");
            bool isSended = false;
            IClientProfile profile = Aliyun.Acs.Core.Profile.DefaultProfile.GetProfile("default", ACCESSKEYID, ACCESSSECRET);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.Method = MethodType.POST;
            request.Domain = "dysmsapi.aliyuncs.com";
            request.Version = "2017-05-25";
            request.Action = "SendSms";
            // request.Protocol = ProtocolType.HTTP;
            request.AddQueryParameters("PhoneNumbers", mobile);
            request.AddQueryParameters("SignName", SignName);//此处为签名名称 为固定
            request.AddQueryParameters("TemplateCode", templateCode);//此处为模板编码 
            if (!isWelcome)
            {
                request.AddQueryParameters("TemplateParam", "{\"code\":\"" + code + "\"}");//自定义参数  验证码 code
            }
            try
            {
                CommonResponse response = client.GetCommonResponse(request);
                var requestjson = Newtonsoft.Json.JsonConvert.SerializeObject(request);
                var result = System.Text.Encoding.UTF8.GetString(response.HttpResponse.Content);

                log.Info(string.Format("时间：{0},【request】：{1},【response】：{2}", DateTime.Now.ToString(), requestjson, result));

                if (!string.IsNullOrEmpty(result))
                {
                    var AliyunSendObj = Newtonsoft.Json.JsonConvert.DeserializeObject<AliyunSendMsg>(result);
                    if (AliyunSendObj != null && AliyunSendObj.Code != null && AliyunSendObj.Code == "OK")
                    {
                        isSended = true;
                    }
                }
                //isSended = true;
            }
            catch (Aliyun.Acs.Core.Exceptions.ServerException e)
            {
                Console.WriteLine(e);
            }
            catch (ClientException e)
            {
                Console.WriteLine(e);
            }
            return isSended;
        }
        private static bool SendMore(string PhoneNumberJson, string templateCode, string content, string SignNameJson, bool isWelcome = false)
        {
            log4net.ILog log = log4net.LogManager.GetLogger("InfoLog");
            bool isSended = false;
            IClientProfile profile = Aliyun.Acs.Core.Profile.DefaultProfile.GetProfile("default", ACCESSKEYID, ACCESSSECRET);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.Method = MethodType.POST;
            request.Domain = "dysmsapi.aliyuncs.com";
            request.Version = "2017-05-25";
            request.Action = "SendBatchSms";
            // request.Protocol = ProtocolType.HTTP;
            request.AddQueryParameters("PhoneNumberJson", PhoneNumberJson);
            request.AddQueryParameters("SignNameJson", SignNameJson);//此处为签名名称 为固定
            request.AddQueryParameters("TemplateCode", templateCode);//此处为模板编码 
            if (!isWelcome)
            {
                request.AddQueryParameters("TemplateParamJson", content);
            }
            try
            {
                CommonResponse response = client.GetCommonResponse(request);
                var requestjson = Newtonsoft.Json.JsonConvert.SerializeObject(request);
                var result = System.Text.Encoding.UTF8.GetString(response.HttpResponse.Content);

                log.Info(string.Format("时间：{0},【request】：{1},【response】：{2}", DateTime.Now.ToString(), requestjson, result));

                if (!string.IsNullOrEmpty(result))
                {
                    var AliyunSendObj = Newtonsoft.Json.JsonConvert.DeserializeObject<AliyunSendMsg>(result);
                    if (AliyunSendObj != null && AliyunSendObj.Code != null && AliyunSendObj.Code == "OK")
                    {
                        isSended = true;
                    }
                }
                //isSended = true;
            }
            catch (Aliyun.Acs.Core.Exceptions.ServerException e)
            {
                Console.WriteLine(e);
            }
            catch (ClientException e)
            {
                Console.WriteLine(e);
            }
            return isSended;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public static bool SendRegMsg(string mobile, string code)
        {
            return Send(mobile, "SMS_168591180", code, "集采云");//注册

        }

        public static bool SendLoginMsg(string mobile, string code)
        {
            return Send(mobile, "SMS_168591178", code, "集采云");//登陆

        }

        public static bool SendBindMsg(string mobile, string code)
        {
            return Send(mobile, "SMS_168591178", code, "集采云");//绑定

        }

        public static bool SendNotice(string mobile, string content)
        {

            return Send(mobile, "SMS_175530440", content, "和轩办公管家");
        }
        /// <summary>
        /// 批量发送推广信息
        /// </summary>
        /// <param name="PhoneNumberJson">手机号码json数组</param>
        /// <param name="content">内容</param>
        /// <param name="SignNameJson">签名数组 与手机号码json数组一一对应</param>
        /// <returns></returns>
        public static bool SendNoticeMore(string PhoneNumberJson, string content, string SignNameJson)
        {
            return SendMore(PhoneNumberJson, "SMS_175571563", content, SignNameJson);
        }
        #endregion
    }

    public class emailmsgObj
    {
        public bool result { get; set; }
        public int statusCode { get; set; }
        public string message { get; set; }

    }


    public class templateparmaritem
    {
        public string content { get; set; }
    }
    public class AliyunSendMsg
    {
        public string Message { get; set; }
        public string RequestId { get; set; }
        public string BizId { get; set; }
        public string Code { get; set; }

    }
}
